#!/usr/bin/env python3
"""
任务 6: 创建结果报告器核心功能
文件: utils/result_reporter.py
实现 display_progress() 函数显示处理进度
实现 log_result() 函数记录单个仓库结果
实现 generate_summary() 函数生成汇总统计
"""

import time
from datetime import datetime
from typing import List, Dict, Any

class ResultReporter:
    """结果报告器"""
    
    def __init__(self, verbose: bool = False):
        """
        初始化结果报告器
        
        Args:
            verbose: 是否启用详细输出
        """
        self.verbose = verbose
        self.start_time = None
        self.processed_count = 0
        self.success_count = 0
        self.failed_count = 0
        self.skipped_count = 0
        self.results = []
    
    def start_processing(self, total_repos: int):
        """
        开始处理
        
        Args:
            total_repos: 仓库总数
        """
        self.start_time = datetime.now()
        self.processed_count = 0
        self.success_count = 0
        self.failed_count = 0
        self.skipped_count = 0
        self.results = []
        
        print(f"开始处理 {total_repos} 个 Git 仓库...")
        print("=" * 60)
    
    def display_progress(self, current_repo: str, repo_count: int, total_repos: int):
        """
        显示处理进度
        
        Args:
            current_repo: 当前处理的仓库
            repo_count: 当前仓库序号
            total_repos: 仓库总数
        """
        self.processed_count = repo_count
        
        # 计算进度百分比
        progress = (repo_count / total_repos) * 100
        
        # 显示进度条
        bar_length = 40
        filled_length = int(bar_length * repo_count // total_repos)
        bar = '█' * filled_length + '-' * (bar_length - filled_length)
        
        print(f"\r进度: [{bar}] {progress:.1f}% ({repo_count}/{total_repos}) "
              f"处理: {current_repo}", end='', flush=True)
    
    def log_result(self, repo_path: str, status: str, output: str = "", error: str = ""):
        """
        记录单个仓库结果
        
        Args:
            repo_path: 仓库路径
            status: 状态 (success/failed/skipped)
            output: 输出信息
            error: 错误信息
        """
        # 更新计数器
        if status == "success":
            self.success_count += 1
        elif status == "failed":
            self.failed_count += 1
        elif status == "skipped":
            self.skipped_count += 1
        
        # 记录结果
        result = {
            "path": repo_path,
            "status": status,
            "output": output,
            "error": error,
            "timestamp": datetime.now().isoformat()
        }
        self.results.append(result)
        
        # 显示详细结果
        if self.verbose:
            print(f"\n仓库: {repo_path}")
            print(f"状态: {status}")
            if output:
                print(f"输出: {output}")
            if error:
                print(f"错误: {error}")
            print("-" * 40)
    
    def generate_summary(self) -> Dict[str, Any]:
        """
        生成汇总统计
        
        Returns:
            Dict[str, Any]: 汇总信息
        """
        end_time = datetime.now()
        duration = end_time - self.start_time
        duration_seconds = duration.total_seconds()
        
        summary = {
            "total_repos": len(self.results),
            "processed_count": self.processed_count,
            "success_count": self.success_count,
            "failed_count": self.failed_count,
            "skipped_count": self.skipped_count,
            "duration_seconds": duration_seconds,
            "start_time": self.start_time.isoformat(),
            "end_time": end_time.isoformat(),
            "success_rate": (self.success_count / max(1, len(self.results))) * 100,
            "results": self.results
        }
        
        return summary
    
    def print_summary(self):
        """打印汇总报告"""
        summary = self.generate_summary()
        
        print("\n" + "=" * 60)
        print("处理完成 - 汇总报告")
        print("=" * 60)
        print(f"总仓库数: {summary['total_repos']}")
        print(f"成功更新: {summary['success_count']}")
        print(f"更新失败: {summary['failed_count']}")
        print(f"跳过处理: {summary['skipped_count']}")
        print(f"成功率: {summary['success_rate']:.1f}%")
        print(f"总耗时: {summary['duration_seconds']:.2f} 秒")
        print(f"平均耗时: {summary['duration_seconds'] / max(1, summary['total_repos']):.2f} 秒/仓库")
        
        if summary['failed_count'] > 0:
            print("\n失败的仓库:")
            for result in summary['results']:
                if result['status'] == 'failed':
                    print(f"  - {result['path']}: {result['error']}")
        
        print("=" * 60)

def test_result_reporter():
    """测试结果报告器"""
    print("测试结果报告器...")
    
    reporter = ResultReporter(verbose=True)
    
    # 开始处理
    reporter.start_processing(5)
    
    # 模拟处理过程
    test_repos = [
        ("/tmp/repo1", "success", "更新成功", ""),
        ("/tmp/repo2", "failed", "", "网络超时"),
        ("/tmp/repo3", "success", "更新成功", ""),
        ("/tmp/repo4", "skipped", "仓库不存在", ""),
        ("/tmp/repo5", "success", "更新成功", "")
    ]
    
    for i, (repo_path, status, output, error) in enumerate(test_repos, 1):
        reporter.display_progress(repo_path, i, 5)
        time.sleep(0.5)  # 模拟处理时间
        reporter.log_result(repo_path, status, output, error)
    
    print()  # 换行
    reporter.print_summary()

if __name__ == "__main__":
    test_result_reporter()